<?php
/**
 * Created by PhpStorm.
 * User: xuyiping
 * Date: 2017/11/22
 * Time: 13:19
 */
/**
 * 量子互助登录路由
 * @author   xuyiping <xuyiping@liangzihuzhu.com.cn>
 * @version 1.0
 */
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Model\User\UserModel;
use Illuminate\Http\Request;

class LoginController extends Controller{

    //用户登录页面
    public function index(Request $request){

        $redirect_url = $request->input('redirect_url');
        if( empty($redirect_url) ){
            $redirect_url = '/admin/main';
        }
        $request->session()->put('G_LOGIN_REDIRECT',$redirect_url);
        return view('Admin/login');
    }

    //登录操作
    public function login(Request $request){
        $login_name = $request->input('login_name');
        $password = $request->input('password');
        if ( !isset($login_name) || empty($login_name) ) {
            
            return response()->json(array(
                'code' => 100001,
                'message' => '登录账号不能为空'
            ));
        }

        if ( !isset($password) || empty($password)) {
            return response()->json(array(
                'code' => 100002,
                'message' => '登录密码不能为空'
            ));
        }

        if ( isset($password) &&  !is_pwd($password)) {
            return response()->json(array(
                'code' => 100003,
                'message' => '登录密码格式不正确'
            ));
        }

        //查询用户是否存在
        $user_data = UserModel::select('userID','userPwd')
            ->where('userID',$login_name)
            ->orWhere('mobile',$login_name)
            ->first();

        if ( empty($user_data)) {
            return response()->json(array(
                'code' => 100004,
                'message' => '该用户不存在'
            ));
        }

        if ( $user_data['userPwd'] != md5($password)) {
            return response()->json(array(
                'code' => 100005,
                'message' => '密码不正确'
            ));
        }

        //保存用户id到session
        $request->session()->put('ADMIN_USER_ID' . session()->getId(), $user_data['userID']);
        $redirect_url = $request->session()->get('G_LOGIN_REDIRECT');

        if (!$redirect_url) {
            $redirect_url = '/admin/main';
        }
        record('sql','登录后台');//记录操作

        return response()->json(array(
            'code' => 200,
            'message' => '登录成功',
            'data' => [
                'redirect_url' => $redirect_url
            ]
        ));


    }

    //退出
    public function logout(Request $request){
        $target_url = "/admin/login";
        $request->session()->forget('ADMIN_USER_ID'.session()->getId());
        header('Location: ' . $target_url);
    }

}